﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using Admin.NET.Application.Entity;
using Admin.NET.Core.Service;
using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Http;
using SqlSugar;

namespace Admin.NET.Application;

/// <summary>
/// 货品信息服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class CommodityinformationService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<Commodityinformation> _commodityinformationRep;
    private readonly ISqlSugarClient _sqlSugarClient;

    public CommodityinformationService(SqlSugarRepository<Commodityinformation> commodityinformationRep, ISqlSugarClient sqlSugarClient)
    {
        _commodityinformationRep = commodityinformationRep;
        _sqlSugarClient = sqlSugarClient;
    }

    /// <summary>
    /// 分页查询货品信息 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询货品信息")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<CommodityinformationOutput>> Page(PageCommodityinformationInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _commodityinformationRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), u => u.ItemName.Contains(input.Keyword) || u.ItemCode.Contains(input.Keyword) || u.Specifications.Contains(input.Keyword) || u.ShelfUnits.Contains(input.Keyword) || u.Remark.Contains(input.Keyword) || u.PrimaryunitBarcode.Contains(input.Keyword) || u.AuxiliaryUnits.Contains(input.Keyword) || u.InventoryList.Contains(input.Keyword) || u.UploadImage.Contains(input.Keyword) || u.UploadAttachments.Contains(input.Keyword))
            .WhereIF(!string.IsNullOrWhiteSpace(input.ItemName), u => u.ItemName.Contains(input.ItemName.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.ItemCode), u => u.ItemCode.Contains(input.ItemCode.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Specifications), u => u.Specifications.Contains(input.Specifications.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.ShelfUnits), u => u.ShelfUnits.Contains(input.ShelfUnits.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Remark), u => u.Remark.Contains(input.Remark.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.PrimaryunitBarcode), u => u.PrimaryunitBarcode.Contains(input.PrimaryunitBarcode.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.AuxiliaryUnits), u => u.AuxiliaryUnits.Contains(input.AuxiliaryUnits.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.InventoryList), u => u.InventoryList.Contains(input.InventoryList.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.UploadImage), u => u.UploadImage.Contains(input.UploadImage.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.UploadAttachments), u => u.UploadAttachments.Contains(input.UploadAttachments.Trim()))
            .WhereIF(input.GoodsID != null, u => u.GoodsID == input.GoodsID)
            .WhereIF(input.DisplayOrder != null, u => u.DisplayOrder == input.DisplayOrder)
            .WhereIF(input.Shelflife != null, u => u.Shelflife == input.Shelflife)
            .WhereIF(input.Earlywarning != null, u => u.Earlywarning == input.Earlywarning)
            .WhereIF(input.Primaryunit != null, u => u.Primaryunit == input.Primaryunit)
            .WhereIF(input.UserID != null, u => u.UserID == input.UserID)
            .WhereIF(input.VendorID != null, u => u.VendorID == input.VendorID)
            .LeftJoin<Goodstype>((u, goods) => u.GoodsID == goods.Id)
            .LeftJoin<Unit>((u, goods, primaryunit) => u.Primaryunit == primaryunit.Id)
            .LeftJoin<Customermanagement>((u, goods, primaryunit, user) => u.UserID == user.Id)
            .LeftJoin<Vendor>((u, goods, primaryunit, user, vendor) => u.VendorID == vendor.Id)
            .Select((u, goods, primaryunit, user, vendor) => new CommodityinformationOutput
            {
                Id = u.Id,
                ItemName = u.ItemName,
                ItemCode = u.ItemCode,
                GoodsID = u.GoodsID,
                GoodsFkDisplayName = $"{goods.GoodsName}",
                Specifications = u.Specifications,
                EnterPrice = u.EnterPrice,
                GooutPrice = u.GooutPrice,
                DisplayOrder = u.DisplayOrder,
                State = u.State,
                ShelfManagement = u.ShelfManagement,
                Shelflife = u.Shelflife,
                ShelfUnits = u.ShelfUnits,
                Earlywarning = u.Earlywarning,
                Remark = u.Remark,
                MultiUnitEnabled = u.MultiUnitEnabled,
                Primaryunit = u.Primaryunit,
                PrimaryunitFkDisplayName = $"{primaryunit.UnitName}",
                PrimaryunitBarcode = u.PrimaryunitBarcode,
                AuxiliaryUnits = u.AuxiliaryUnits,
                InventoryList = u.InventoryList,
                UploadImage = u.UploadImage,
                UploadAttachments = u.UploadAttachments,
                IsDelete = u.IsDelete,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
                UserID = u.UserID,
                UserFkDisplayName = $"{user.CustomerName}",
                VendorID = u.VendorID,
                VendorFkDisplayName = $"{vendor.VendorName}",
            });
		return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取货品信息详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取货品信息详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<Commodityinformation> Detail([FromQuery] QueryByIdCommodityinformationInput input)
    {
        return await _commodityinformationRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加货品信息 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加货品信息")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddCommodityinformationInput input)
    {
        var entity = input.Adapt<Commodityinformation>();
        return await _commodityinformationRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新货品信息 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新货品信息")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdateCommodityinformationInput input)
    {
        var entity = input.Adapt<Commodityinformation>();
        await _commodityinformationRep.AsUpdateable(entity)
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除货品信息 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除货品信息")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeleteCommodityinformationInput input)
    {
        var entity = await _commodityinformationRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _commodityinformationRep.FakeDeleteAsync(entity);   //假删除
        //await _commodityinformationRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除货品信息 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除货品信息")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeleteCommodityinformationInput> input)
    {
        var exp = Expressionable.Create<Commodityinformation>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _commodityinformationRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _commodityinformationRep.FakeDeleteAsync(list);   //假删除
        //return await _commodityinformationRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 获取下拉列表数据 🔖
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取下拉列表数据")]
    [ApiDescriptionSettings(Name = "DropdownData"), HttpPost]
    public async Task<Dictionary<string, dynamic>> DropdownData(DropdownDataCommodityinformationInput input)
    {
        var goodsIDData = await _commodityinformationRep.Context.Queryable<Goodstype>()
            .InnerJoinIF<Commodityinformation>(input.FromPage, (u, r) => u.Id == r.GoodsID)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.GoodsName}"
            }).ToListAsync();
        var primaryunitData = await _commodityinformationRep.Context.Queryable<Unit>()
            .InnerJoinIF<Commodityinformation>(input.FromPage, (u, r) => u.Id == r.Primaryunit)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.UnitName}"
            }).ToListAsync();
        var userIDData = await _commodityinformationRep.Context.Queryable<Customermanagement>()
            .InnerJoinIF<Commodityinformation>(input.FromPage, (u, r) => u.Id == r.UserID)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.CustomerName}"
            }).ToListAsync();
        var vendorIDData = await _commodityinformationRep.Context.Queryable<Vendor>()
            .InnerJoinIF<Commodityinformation>(input.FromPage, (u, r) => u.Id == r.VendorID)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.VendorName}"
            }).ToListAsync();
        return new Dictionary<string, dynamic>
        {
            { "goodsID", goodsIDData },
            { "primaryunit", primaryunitData },
            { "userID", userIDData },
            { "vendorID", vendorIDData },
        };
    }
    
    /// <summary>
    /// 导出货品信息记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出货品信息记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PageCommodityinformationInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportCommodityinformationOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        return ExcelHelper.ExportTemplate(list, "货品信息导出记录");
    }
    
    /// <summary>
    /// 下载货品信息数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载货品信息数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportCommodityinformationOutput>(), "货品信息导入模板", (_, info) =>
        {
            if (nameof(ExportCommodityinformationOutput.GoodsFkDisplayName) == info.Name) return _commodityinformationRep.Context.Queryable<Goodstype>().Select(u => $"{u.GoodsName}").Distinct().ToList();
            if (nameof(ExportCommodityinformationOutput.PrimaryunitFkDisplayName) == info.Name) return _commodityinformationRep.Context.Queryable<Unit>().Select(u => $"{u.UnitName}").Distinct().ToList();
            if (nameof(ExportCommodityinformationOutput.UserFkDisplayName) == info.Name) return _commodityinformationRep.Context.Queryable<Customermanagement>().Select(u => $"{u.CustomerName}").Distinct().ToList();
            if (nameof(ExportCommodityinformationOutput.VendorFkDisplayName) == info.Name) return _commodityinformationRep.Context.Queryable<Vendor>().Select(u => $"{u.VendorName}").Distinct().ToList();
            return null;
        });
    }
    
    /// <summary>
    /// 导入货品信息记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入货品信息记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (this)
        {
            var stream = ExcelHelper.ImportData<ImportCommodityinformationInput, Commodityinformation>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    // 链接 货品类型
                    var goodsIDLabelList = pageItems.Where(x => x.GoodsFkDisplayName != null).Select(x => x.GoodsFkDisplayName).Distinct().ToList();
                    if (goodsIDLabelList.Any()) {
                        var goodsIDLinkMap = _commodityinformationRep.Context.Queryable<TreeParentOutputs>().Where(u => goodsIDLabelList.Contains($"{u.GoodsName}")).ToList().ToDictionary(u => $"{u.GoodsName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.GoodsID = goodsIDLinkMap.GetValueOrDefault(e.GoodsFkDisplayName ?? "");
                            if (e.GoodsID == null) e.Error = "货品类型链接失败";
                        });
                    }
                    // 链接 主单位
                    var primaryunitLabelList = pageItems.Where(x => x.PrimaryunitFkDisplayName != null).Select(x => x.PrimaryunitFkDisplayName).Distinct().ToList();
                    if (primaryunitLabelList.Any()) {
                        var primaryunitLinkMap = _commodityinformationRep.Context.Queryable<Unit>().Where(u => primaryunitLabelList.Contains($"{u.UnitName}")).ToList().ToDictionary(u => $"{u.UnitName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.Primaryunit = primaryunitLinkMap.GetValueOrDefault(e.PrimaryunitFkDisplayName ?? "");
                            if (e.Primaryunit == null) e.Error = "主单位链接失败";
                        });
                    }
                    // 链接 客户名称
                    var userIDLabelList = pageItems.Where(x => x.UserFkDisplayName != null).Select(x => x.UserFkDisplayName).Distinct().ToList();
                    if (userIDLabelList.Any()) {
                        var userIDLinkMap = _commodityinformationRep.Context.Queryable<Customermanagement>().Where(u => userIDLabelList.Contains($"{u.CustomerName}")).ToList().ToDictionary(u => $"{u.CustomerName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.UserID = userIDLinkMap.GetValueOrDefault(e.UserFkDisplayName ?? "");
                            if (e.UserID == null) e.Error = "客户名称链接失败";
                        });
                    }
                    // 链接 供应商
                    var vendorIDLabelList = pageItems.Where(x => x.VendorFkDisplayName != null).Select(x => x.VendorFkDisplayName).Distinct().ToList();
                    if (vendorIDLabelList.Any()) {
                        var vendorIDLinkMap = _commodityinformationRep.Context.Queryable<Vendor>().Where(u => vendorIDLabelList.Contains($"{u.VendorName}")).ToList().ToDictionary(u => $"{u.VendorName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.VendorID = vendorIDLinkMap.GetValueOrDefault(e.VendorFkDisplayName ?? "");
                            if (e.VendorID == null) e.Error = "供应商链接失败";
                        });
                    }
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.UserID == null){
                            x.Error = "客户名称不能为空";
                            return false;
                        }
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.VendorID == null){
                            x.Error = "供应商不能为空";
                            return false;
                        }
                        return true;
                    }).Adapt<List<Commodityinformation>>();
                    
                    var storageable = _commodityinformationRep.Context.Storageable(rows)
                        .SplitError(it => it.Item.ItemName?.Length > 32, "货品名称长度不能超过32个字符")
                        .SplitError(it => it.Item.ItemCode?.Length > 32, "货品编号长度不能超过32个字符")
                        .SplitError(it => it.Item.Specifications?.Length > 32, "规格型号长度不能超过32个字符")
                        .SplitError(it => it.Item.ShelfUnits?.Length > 32, "保质期单位长度不能超过32个字符")
                        .SplitError(it => it.Item.Remark?.Length > 200, "备注长度不能超过200个字符")
                        .SplitError(it => it.Item.PrimaryunitBarcode?.Length > 32, "条码长度不能超过32个字符")
                        .SplitError(it => it.Item.AuxiliaryUnits?.Length > 1000, "辅助单位长度不能超过1000个字符")
                        .SplitError(it => it.Item.InventoryList?.Length > 1000, "库存信息长度不能超过1000个字符")
                        .SplitError(it => it.Item.UploadImage?.Length > 2000, "上传图片长度不能超过2000个字符")
                        .SplitError(it => it.Item.UploadAttachments?.Length > 2000, "上传附件长度不能超过2000个字符")
                        .SplitInsert(_ => true)
                        .ToStorage();
                    
                    storageable.BulkCopy();
                    storageable.BulkUpdate();
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
}
